<template>
  <el-dialog v-model="props.uploadOp2Visible" title="上传op2文件" width="500" destroy-on-close :before-close="handleVisible">
    <el-form size="small" :rules="rules" ref="uploadOp2Ref" :model="formData" label-position="right" label-width="150px">
      <el-form-item label="类型" prop="type">
        <el-cascader v-model="formData.type" :options="treeData" :props="typeProps" clearable placeholder="请选择" />
      </el-form-item>
      <el-form-item label="op2批次展示名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入" :disabled="modalType === 'modify'" />
      </el-form-item>
      <el-form-item label="上传文件" prop="file" v-if="modalType != 'modify'">
        <el-upload
          :on-remove="handleRemove"
          :file-list="fileList"
          @change="handleChange"
          :show-file-list="true"
          :auto-upload="false"
          :multiple="false"
          :limit="1"
          action="#"
        >
          <template #trigger>
            <el-button size="small" type="primary" icon="UploadFilled">添加文件</el-button>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="handleVisible">取消</el-button>
        <el-button size="small" type="primary" @click="submitAdd"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
    
<script name="uploadOp2" setup>
import { treeData } from '../resultLibrary.js';
import axios from 'axios';
import { getToken } from '@/utils/auth';
import { updateResult } from '@/api/resultLibrary';

const typeProps = { multiple: false };
const props = defineProps(['uploadOp2Visible', 'rowData']);
const emit = defineEmits(['close']);
const fileList = ref([]);
const uploadOp2Ref = ref(null);
const submitFile = ref(null);
const modalType = props?.rowData ? 'modify' : 'add';
const { proxy } = getCurrentInstance();
// 表单校验规则
const rules = ref({
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  name: [{ required: true, message: '请输入展示名称', trigger: 'blur' }],
  file: [{ required: true, message: '请上传文件', trigger: 'blur' }]
});
const formData = ref({
  type: '',
  name: props?.rowData?.resultName,
  file: props?.rowData?.originalName
});
//处理数据
if (props?.rowData?.resultScope) {
  formData.value.type = [props?.rowData?.applicableResult, props?.rowData?.resultSeries, props?.rowData?.loadConditions, props?.rowData?.resultScope];
} else if (props?.rowData?.loadConditions) {
  formData.value.type = [props?.rowData?.applicableResult, props?.rowData?.resultSeries, props?.rowData?.loadConditions];
} else {
  formData.value.type = [props?.rowData?.applicableResult, props?.rowData?.resultSeries];
}

const handleRemove = () => {
  fileList.value = [];
  formData.value.file = null;
};
const handleChange = (file) => {
  formData.value.file = file;
  submitFile.value = file;
  uploadOp2Ref.value.validate();
};
// 通知父组件
const handleVisible = (modalType) => {
  emit('close', { type: 'add', data: { type: modalType === 'refesh' ? 'refesh' : '' } });
};
// 提交数据
const submitAdd = () => {
  uploadOp2Ref.value.validate((valid) => {
    if (!valid) {
      return false;
    } else {
      const params = new FormData();
      const metadata = formData.value;
      const type = metadata.type;
      params.append('applicableResult', type[0] || '');
      params.append('resultSeries', type[1] || '');
      params.append('loadConditions', type[2] || '');
      params.append('resultScope', type[3] || '');
      let VITE_APP_BASE_API = '/dev-api';
      if (import.meta.env.MODE === 'production') {
        VITE_APP_BASE_API = '/prod-api';
      }
      let url = '/result/save';
      if (modalType === 'modify') {
        const paramData = {
          applicableResult:type[0] || '',
          resultSeries:type[1] || '',
          loadConditions:type[2] || '',
          resultScope:type[3] || '',
          resultId:props?.rowData?.resultId
        }
        updateResult(paramData).then(res=>{
          if(res){
            proxy?.$modal.msgSuccess('修改成功');
            handleVisible('refesh');
          }
        })
        return false;
      } else {
        metadata.resultType = metadata.file?.name.slice(metadata.file?.name.lastIndexOf('.'));
        params.append('resultType', metadata.resultType);
        params.append('file', submitFile.value.raw);
        params.append('resultName', metadata?.name);
      }
      axios
        .post(`${VITE_APP_BASE_API}${url}`, params, {
          headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + getToken() }
        })
        .then((res) => {
          proxy?.$modal.msgSuccess('上传成功');
          handleVisible('refesh');
          fileList.value = [];
        });
    }
  });
};
</script>
  <style scoped>
.text-red {
  color: red;
  margin-top: 10px;
}
:deep(.el-cascader) {
  width: 100%;
}
</style>